package util.serviceUtil;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.text.R;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import data.SharedPreferencesUtils;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.Url;
import view.diaLogView.EditionDialog;

/**
 * Created by Administrator on 2016/7/25.
 * 用于下载app
 */
public class UpdataService extends Service {
    private String mAppUri;                     //app的下载地址
    private static String mAppUriVer,mFileUrl;                 //app的版本号
    private File mFile,fileUia;

    private static TextView mTextView,mTextViewHint;      //升级弹出框中的确定按钮
    public static void getTextView(TextView textView,TextView textviewHint){
        mTextView = textView;
        mTextViewHint = textviewHint;
    }
    @Nullable @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override public int onStartCommand(Intent intent, final int flags, int startId) {
        if(intent !=null){
            mAppUri = intent.getStringExtra("url");
            mAppUriVer = intent.getStringExtra("ver");
            mFileUrl = intent.getStringExtra("filepath");
            downLoadApk(mAppUri);
            mTextViewHint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(fileUia !=null && fileUia.length()>0){
                        LogUtil.eE("",".......文件名称....."+fileUia.getName());
                        LogUtil.eE("",".......文件的相对路径....."+fileUia.getPath());
                        //JumpActivityUtils.getInstance().jumpInstallAPK(UpdataService.this,fileUia);
                        JumpActivityUtils.getInstance().installApp(UpdataService.this,mFileUrl);
                    }else {
                        downLoadApk(mAppUri);
                    }

                }
            });
        }
        return super.onStartCommand(intent, flags, startId);

    }

    /**
     * 下载
     * /storage/emulated/0/1514515758773.apk
     */
    private void downLoadApk(String url) {
        LogUtil.eE("","           url..."+url);
        File root = Environment.getExternalStorageDirectory();
        //mFileUrl =root.getAbsolutePath()+File.separator + System.currentTimeMillis() + ".apk";
        LogUtil.eE("","          file .."+mFileUrl);
        RequestParams params = new RequestParams(url);
        params.setSaveFilePath(mFileUrl);
        params.setAutoResume(true);
        params.setCancelFast(true);
        x.http().get(params,new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                LogUtil.eE("","onSuccess   "+result);
                if(result.length() >0){
                    fileUia = result;
                    mTextViewHint.setText("下载完成可安装");
                    JumpActivityUtils.getInstance().installApp(UpdataService.this,mFileUrl);
                    SharedPreferencesUtils.setParam(UpdataService.this, HomeUtil.mHUAppVer,mAppUriVer);
                    brokenNetwork();
                }else {
                    Toast.makeText(getApplicationContext(),"下载失败",Toast.LENGTH_SHORT).show();
                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.eE("","onError   ");
                Toast.makeText(getApplicationContext(),"下载失败",Toast.LENGTH_SHORT).show();
                stopSelf();
            }
            @Override
            public void onCancelled(Callback.CancelledException cex) {
                LogUtil.eE("","onCancelled   ");
                stopSelf();
            }
            @Override
            public void onFinished() {
                LogUtil.eE("","onFinished   ");
                stopSelf();
            }
            @Override
            public void onWaiting() {
                LogUtil.eE("","onWaiting   ");
            }
            @Override
            public void onStarted() {
                LogUtil.eE("","onStarted   ");
            }
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                float prog = ((float) current / (float) total) * 100;
                LogUtil.eE("","prog   "+prog);
                String hint = "已下载"+(int)prog+"%";
                mTextViewHint.setText(hint);
                if(prog>60){
                    mTextViewHint.setTextColor(getApplicationContext().getResources().getColor(R.color.bg_color));
                }
                if(prog>0){
                    EditionDialog.getInstance().getLLayoutVisibility();
                }
                EditionDialog.getInstance().getProgressBar((int)prog);
            }
        });
    }

    @Override public void onDestroy() {
        super.onDestroy();
        stopSelf();
    }

    private void brokenNetwork(){
        if( Url.getUrlNew().getNETWORKING_ATATE() == 1){
            NetWorkstateUtil.getInstance().getBrokenNetwork(this, new HomeUtil.OnHomeUtilClickListener() {
                @Override
                public void onItemClick(String type) {
                    if(type.equals("ok")){
                        Url.getUrlNew().setNETWORKING_ATATE(0);
                    }
                }
            },1);
        }
    }
}
